﻿using Practice.IRepository;
using Practice.IService;
using Practice.PH4_2104A.IRepository;
using Practice.PH4_2104A.Shopping.SevenLayerFramework.Domin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice.Service
{
    /// <summary>
    /// 分类服务实现
    /// </summary>
    public class CategoryService : ICategoryService
    {
        ICategoryRepository _repository;
        IUnitOfWork _unitOfWork;

        public CategoryService(ICategoryRepository repository, IUnitOfWork unitOfWork)
        {
            _repository = repository;
            _unitOfWork = unitOfWork;
        }

        //删除
        public int Delete(CategoryModel model)
        {
            _repository.Delete(model);
            return _unitOfWork.SaveChanges();
        }

        //获取数据
        public IQueryable<CategoryModel> GetAll()
        {
            return _repository.GetAll();
        }

        //添加分类
        public int Insert(CategoryModel model)
        {
            _repository.Insert(model);
            return _unitOfWork.SaveChanges();
        }

        //修改分类
        public int Update(CategoryModel model)
        {
            _repository.Update(model);
            return _unitOfWork.SaveChanges();
        }



        /// <summary>
        /// 获取递归数据
        /// </summary>
        /// <returns></returns>
        public dynamic GetRecurseCategory()
        {
            var list = _repository.GetAll().ToList();
            var data = this.GetRecurseCategory(list, Guid.Empty.ToString());
            return data;
        }


        /// <summary>
        /// 分类的递归实现
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id"></param>
        private List<dynamic> GetRecurseCategory(List<CategoryModel> list,string id)
        {
            List<dynamic> result = new(); //用来保存查询结果的

            var data = list.Where(x=>x.ParentId.ToString().Equals(id));
            data.ToList().ForEach(x =>
            {
                //调用自己，递归查询
                var d = this.GetRecurseCategory(list,x.Id.ToString());

                result.Add(new
                {
                    id = x.Id,
                    parentId = x.ParentId,
                    name = x.Name,
                    children = d != null && d.Count > 0 ? d : null
                }) ;
            });

            return result;
        }
    }
}
